<template>
  <view class="sms-container">
    <!-- 手机号输入部分 -->
    <view class="form-item">
      <text class="label">手机号码</text>
      <input 
        v-model="phone" 
        type="number" 
        placeholder="请输入手机号码"
        maxlength="11"
      />
    </view>
    
    <!-- 验证码部分 -->
    <view class="form-item">
      <text class="label">验证码</text>
      <view class="code-input">
        <input 
          v-model="code" 
          type="number" 
          placeholder="请输入验证码"
          maxlength="6"
        />
        <button 
          class="send-btn" 
          :disabled="countdown > 0 || !validPhone"
          @click="handleSendCode"
        >
          {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
        </button>
      </view>
    </view>
    
    <!-- 腾讯验证码组件（官方标准组件） -->
    <t-captcha
      id="tcaptcha"
      :app-id="captchaAppId"
      @verify="onVerify"
      @ready="onReady"
      @close="onClose"
      @error="onError"
      theme-color="#1A79FF"
    />
    
    <button class="submit-btn" @click="submit">登录</button>
  </view>
</template>

<script>
export default {
  data() {
	  return {
		captchaAppId: '195057918', // 替换为你的真实CaptchaAppId
		phone: '',
		code: '',
		countdown: 0,
		captchaInstance: null // 保存验证码实例
	  }
	},
  computed: {
    validPhone() {
      return /^1[3-9]\d{9}$/.test(this.phone)
    }
  },
  methods: {
    // 获取验证码
	handleSendCode() {
	  if (!this.validPhone) {
		uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
		return;
	  }
	  
	  // 获取验证码组件实例并显示
	  this.getCaptchaInstance().show();
	},
    // 获取验证码组件实例
	getCaptchaInstance() {
	  if (!this.captchaInstance) {
		this.captchaInstance = this.selectComponent('#tcaptcha');
	  }
	  return this.captchaInstance;
	},
	// 验证码准备就绪
	onReady() {
	  console.log('验证码准备就绪');
	},
    
    // 验证成功回调
	async onVerify(e) {
	  if (e.detail.ret === 0) {
		console.log('验证成功 ticket:', e.detail.ticket);
		
		// 显示加载状态
		uni.showLoading({ title: '发送中...', mask: true });
		
		try {
		  // 1. 验证腾讯验证码
		  const verifyRes = await this.verifyWithBackend(e.detail.ticket);
		  
		  if (verifyRes) {
			// 2. 发送短信验证码
			await this.sendSMSCode();
		  }
		} catch (error) {
		  console.error('发送验证码失败:', error);
		  // 验证失败时刷新验证码
		  this.getCaptchaInstance().refresh();
		} finally {
		  uni.hideLoading();
		}
	  }
	},
    
    // 验证码关闭
	onClose(e) {
	  if (e.detail.ret === 2) {
		console.log('用户主动关闭验证码');
	  }
	},
	
	// 验证码出错
	onError(e) {
	  console.error('验证码错误:', e.detail.errMsg);
	  uni.showToast({
		title: '验证码加载失败',
		icon: 'none'
	  });
	},
    
    // 向后端验证ticket
    async verifyWithBackend(ticket, randstr) {
      try {
        const res = await uni.request({
          url: this.$baseUrl +"/user_api/sms/code/verify",
          method: 'POST',
          data: { ticket, randstr }
        });
        return res.data.code==0;
      } catch (error) {
        console.error('验证请求失败:', error);
        return false;
      }
    },
    
    // 发送短信验证码
    async sendSMSCode() {
      try {
        const res = await uni.request({
          url: this.$baseUrl + '/user_api/sms/send',
          method: 'POST',
          data: { phone: this.phone }
        });
        
        if (res.data.code === 0) {
          uni.showToast({ title: '验证码发送成功' });
          this.startCountdown();
        } else {
          throw new Error(res.data.msg || '验证码发送失败');
        }
      } catch (error) {
        console.error('发送短信失败:', error);
        throw error;
      }
    },
    
    // 开始倒计时
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    
    // 提交登录
    submit() {
      if (!this.validPhone) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }
      
      if (!this.code) {
        uni.showToast({ title: '请输入验证码', icon: 'none' });
        return;
      }
      
      uni.showLoading({ title: '登录中...', mask: true });
      
      uni.request({
        url: this.$baseUrl + '/user_api/user/sms/login',
        method: 'POST',
        data: { phone: this.phone, code: this.code },
        success: (res) => {
          uni.hideLoading();
          if (res.data.code === 0) {
            uni.setStorageSync('userId', res.data.data.userId);
            uni.setStorageSync('nickName', res.data.data.nickName || '用户' + this.phone.slice(-4));
            uni.showToast({ title: '登录成功' });
            uni.navigateBack();
          } else {
            uni.showToast({ title: res.data.msg || '登录失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.sms-container {
  padding: 60rpx;
  
  .form-item {
    margin-bottom: 40rpx;
    
    .label {
      display: block;
      margin-bottom: 20rpx;
      font-size: 30rpx;
      color: #666;
    }
    
    input {
      height: 90rpx;
      padding: 0 20rpx;
      background: #f5f5f5;
      border-radius: 8rpx;
      font-size: 30rpx;
    }
    
    .code-input {
      display: flex;
      align-items: center;
      
      input {
        flex: 1;
        margin-right: 20rpx;
      }
      
      .send-btn {
        width: 220rpx;
        height: 90rpx;
        line-height: 90rpx;
        font-size: 28rpx;
        background: linear-gradient(to right, #6a11cb, #2575fc);
        color: white;
        border-radius: 8rpx;
        transition: all 0.3s;
        
        &[disabled] {
          background: #ccc;
          opacity: 0.7;
        }
      }
    }
  }
  
  .submit-btn {
    margin-top: 80rpx;
    height: 90rpx;
    line-height: 90rpx;
    background: linear-gradient(to right, #6a11cb, #2575fc);
    color: white;
    font-size: 32rpx;
    border-radius: 45rpx;
    box-shadow: 0 4rpx 12rpx rgba(106, 17, 203, 0.3);
  }
}

/* 腾讯验证码组件样式调整 */
::v-deep .captcha-container {
  z-index: 9999;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>